package com.bigmodel.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bigmodel.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WebChatService {

    private static  String access_token = "";
    private static final String corpid = "ww66a46b9d7ff0633c";
    private static final String corpsecret = "TMwbxgndcC_NiBQFR7MMUjMfk-RKLlfVS6CwxG73tF4";

    private static void getAccessToken(){
        String gettoken_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
        log.info("request gettoken_url {}",gettoken_url);
        String response_token = HttpUtil.get(gettoken_url);
        log.info("response gettoken {}",response_token);
        JSONObject tokenObject = JSONUtil.parseObj(response_token);
        access_token = tokenObject.getStr("access_token");
    }

    /**
     * 获取用户信息
     * @return
     */
    public static String getuserinfo(String code) {

        if(ObjectUtil.isEmpty(access_token)){
            getAccessToken();
        }

        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token="+access_token+"&code="+code;
        log.info("request getuserinfo url {}",url);
        String responseStr = HttpUtil.get(url);
        log.info("response getuserinfo  {}",responseStr);
        JSONObject jsonObject = JSONUtil.parseObj(responseStr);
        if(jsonObject!=null&&"42001".equals(jsonObject.getStr("errcode"))){
            getAccessToken();
            url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token="+access_token+"&code="+code;
            log.info("request getuserinfo url {}",url);
            responseStr = HttpUtil.get(url);
            log.info("response getuserinfo  {}",responseStr);
        }
        jsonObject = JSONUtil.parseObj(responseStr);
        String user_ticket = jsonObject.getStr("user_ticket");

        return getuserdetail(user_ticket);
    }


    private static String getuserdetail(String user_ticket) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token="+access_token;
        log.info("request getuserdetail url  {}",url);
        Map<String,Object> params = new HashMap<>();
        params.put("user_ticket",user_ticket);

        HttpRequest reuqest = HttpUtil.createPost(url);
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        reuqest.addHeaders(headers);
        reuqest.body(JSONUtil.toJsonStr(params));
        String responseStr = reuqest.execute().body();

        log.info("response getuserdetail {}",responseStr);
        return responseStr;
    }




}
